<template>
  <view class="container">
    <view class="header">
      <text class="title">微信登录测试</text>
    </view>
    
    <view class="content">
      <view class="step-section">
        <text class="step-title">步骤1: 获取微信登录凭证</text>
        <button class="login-btn" @click="getWechatCode" :disabled="loading">
          {{ loading ? '获取中...' : '获取微信Code' }}
        </button>
        <view v-if="wechatCode" class="result-box">
          <text class="result-label">Code:</text>
          <text class="result-text">{{ wechatCode }}</text>
        </view>
      </view>
      
      <view class="step-section">
        <text class="step-title">步骤2: 获取OpenId</text>
        <button class="login-btn" @click="getOpenId" :disabled="!wechatCode || loading">
          {{ loading ? '获取中...' : '获取OpenId' }}
        </button>
        <view v-if="openId" class="result-box">
          <text class="result-label">OpenId:</text>
          <text class="result-text">{{ openId }}</text>
        </view>
        <view v-if="sessionKey" class="result-box">
          <text class="result-label">SessionKey:</text>
          <text class="result-text">{{ sessionKey }}</text>
        </view>
        <view v-if="unionId" class="result-box">
          <text class="result-label">UnionId:</text>
          <text class="result-text">{{ unionId }}</text>
        </view>
      </view>
      
      <view class="step-section">
        <text class="step-title">完整登录流程</text>
        <button class="login-btn primary" @click="fullWechatLogin" :disabled="loading">
          {{ loading ? '登录中...' : '一键微信登录' }}
        </button>
      </view>
      
      <view v-if="errorMsg" class="error-box">
        <text class="error-text">{{ errorMsg }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/api/config.js'

export default {
  data() {
    return {
      wechatCode: '',
      openId: '',
      sessionKey: '',
      unionId: '',
      loading: false,
      errorMsg: ''
    }
  },
  
  methods: {
    // 获取微信登录凭证
    getWechatCode() {
      this.loading = true
      this.errorMsg = ''
      
      console.log('=== 开始获取微信登录凭证 ===')
      console.log('调用 uni.login，provider: weixin')
      
      uni.login({
        provider: 'weixin',
        success: (res) => {
          console.log('uni.login 返回结果:', res)
          console.log('微信Code获取成功:', res.code)
          this.wechatCode = res.code
          this.loading = false
          uni.showToast({
            title: '获取Code成功',
            icon: 'success'
          })
          console.log('=== 获取微信登录凭证结束 ===')
        },
        fail: (err) => {
          console.error('微信登录失败:', err)
          console.error('错误详情:', JSON.stringify(err))
          this.errorMsg = '获取微信Code失败: ' + (err.errMsg || JSON.stringify(err))
          this.loading = false
          uni.showToast({
            title: '获取Code失败',
            icon: 'error'
          })
          console.log('=== 获取微信登录凭证结束 ===')
        }
      })
    },
    
    // 通过code获取openId
    async getOpenId() {
      if (!this.wechatCode) {
        uni.showToast({
          title: '请先获取Code',
          icon: 'error'
        })
        return
      }
      
      this.loading = true
      this.errorMsg = ''
      
      // 开始获取微信OpenId（移除敏感日志）
      
      try {
        const requestUrl = `${config.BASE_URL}${API_CONFIG.WECHAT_LOGIN.GET_OPENID}`
        const requestData = {
          code: this.wechatCode,
          orgId: config.ORG_ID,
          appId: config.WECHAT_APPID
        }
        
        // 请求参数已构建（不输出敏感信息）
        
        // 调用后端接口获取openId
        const [error, response] = await uni.request({
          url: requestUrl,
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: requestData
        })
        
        if (error) {
          console.error('请求失败:', error)
          throw new Error('网络请求失败: ' + JSON.stringify(error))
        }
        
        // 后端响应已返回（不输出敏感信息）
        
        if (response.data.code !== 200) {
          console.error('后端接口返回错误:', response.data.msg)
          throw new Error(response.data.msg || '后端接口调用失败')
        }
        
        const result = response.data.data
        this.openId = result.openid
        this.sessionKey = result.sessionKey
        this.unionId = result.unionid || '未绑定开放平台'
        
        
        uni.showToast({
          title: '获取OpenId成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('获取OpenId失败:', error)
        // console.error('错误详情:', JSON.stringify(error))
        this.errorMsg = '获取OpenId失败: ' + error.message
        uni.showToast({
          title: '获取OpenId失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
        // 获取微信OpenId流程结束
      }
    },
    
    // 调用后端接口获取微信用户信息
    async callWechatApi() {
      // 开始调用后端微信登录接口（移除敏感日志）
      
      const requestUrl = `${config.BASE_URL}${API_CONFIG.WECHAT_LOGIN.GET_OPENID}`
      const requestData = {
        code: this.wechatCode,
        orgId: config.ORG_ID,
        appId: config.WECHAT_APPID
      }
      
      // 请求参数已构建（不输出敏感信息）
      console.log('请求头:', {
        'Content-Type': 'application/json'
      })
      
      return new Promise((resolve, reject) => {
        uni.request({
          url: requestUrl,
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: requestData,
          success: (res) => {
            console.log('后端API响应状态码:', res.statusCode)
            console.log('后端API响应头:', res.header)
            console.log('后端API响应数据:', res.data)
            
            if (res.data.code !== 200) {
              console.error('后端接口返回错误:', res.data.msg)
              reject(new Error(res.data.msg || '后端接口调用失败'))
            } else {
              console.log('后端接口调用成功，返回数据:', res.data.data)
              resolve(res.data.data)
            }
          },
          fail: (err) => {
            console.error('后端API请求失败:', err)
            console.error('错误详情:', JSON.stringify(err))
            reject(new Error('网络请求失败: ' + (err.errMsg || JSON.stringify(err))))
          },
          complete: () => {
            console.log('=== 后端微信登录接口调用结束 ===')
          }
        })
      })
    },
    
    // 完整的微信登录流程
    async fullWechatLogin() {
      this.loading = true
      this.errorMsg = ''
      this.wechatCode = ''
      this.openId = ''
      this.sessionKey = ''
      this.unionId = ''
      
      console.log('=== 开始一键微信登录流程 ===')
      
      try {
        // 步骤1: 获取微信Code
        console.log('步骤1: 获取微信Code')
        console.log('调用 uni.login，provider: weixin')
        
        await new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: (res) => {
              console.log('uni.login 返回结果:', res)
              console.log('微信Code获取成功:', res.code)
              this.wechatCode = res.code
              resolve(res)
            },
            fail: (err) => {
              console.error('uni.login 失败:', err)
              reject(err)
            }
          })
        })
        
        // 等待一下，模拟真实场景
        console.log('等待500ms，模拟真实场景延迟')
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 步骤2: 获取OpenId
        console.log('步骤2: 调用后端接口获取OpenId')
        const response = await this.callWechatApi()
        
        this.openId = response.openid
        this.sessionKey = response.sessionKey
        this.unionId = response.unionid || '未绑定开放平台'
        
        console.log('一键登录完成，最终结果:')
        console.log('- openId:', this.openId)
        console.log('- sessionKey:', this.sessionKey)
        console.log('- unionId:', this.unionId)
        
        uni.showToast({
          title: '微信登录成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('微信登录失败:', error)
        console.error('错误详情:', JSON.stringify(error))
        this.errorMsg = '微信登录失败: ' + error.message
        uni.showToast({
          title: '登录失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
        console.log('=== 一键微信登录流程结束 ===')
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 40rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 60rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.content {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.step-section {
  margin-bottom: 60rpx;
  padding-bottom: 40rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.step-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.step-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  background-color: #07c160;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  margin-bottom: 30rpx;
}

.login-btn:disabled {
  background-color: #ccc;
}

.login-btn.primary {
  background-color: #1aad19;
  font-weight: bold;
}

.result-box {
  background-color: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.result-label {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #666;
  margin-bottom: 10rpx;
}

.result-text {
  display: block;
  font-size: 26rpx;
  color: #333;
  word-break: break-all;
  line-height: 1.5;
}

.error-box {
  background-color: #fff5f5;
  border: 2rpx solid #fed7d7;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-top: 30rpx;
}

.error-text {
  color: #e53e3e;
  font-size: 28rpx;
  line-height: 1.5;
}
</style>
